package com.youkeyi.ddy.cloud.gateway.filter;

import brave.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * YoukeyiLogTraceIdFilter
 *
 * @Author liuxiawang
 * @Date 2024/7/4 3:40 PM
 * @Location shenzhen.china
 */
@Slf4j
@Component
public class YoukeyiLogTraceIdFilter implements GlobalFilter, Ordered {

    private final Tracer tracer;

    public YoukeyiLogTraceIdFilter(Tracer tracer) {
        this.tracer = tracer;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = tracer.currentSpan().context().traceIdString();
        exchange.getResponse().getHeaders().set("traceId", traceId);

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        log.info("请求路径: " + path);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -99;
    }
}
